// code modified by Hemiola SUN, 2005-04-14 and fixed by onemen

if(!window.tablib || tablib.version < 20051128) var tablib = { version : [20051128], init : function(){
 if(getBrowser().TMmoveTabTo) return;

if(!getBrowser().moveTabTo) {

// prevent click on close tab button to select tab in FF 1.0.x
if (gIsOldBrowser){
  var _setter = gBrowser.mTabContainer.__lookupSetter__("selectedItem");
  eval("_setter ="+_setter.toString().replace(
    'if (!val.selected) {',
    'if (val.onclosebutton) { delete val.onclosebutton; return this.selectedItem; } \ $&'
  ));
  gBrowser.mTabContainer.__defineGetter__("selectedItem", gBrowser.mTabContainer.__lookupGetter__("selectedItem"));
  gBrowser.mTabContainer.__defineSetter__("selectedItem", _setter);
}

gBrowser.__defineGetter__("mTabs", function(){return gBrowser.mTabContainer.childNodes;});

gBrowser.__defineGetter__("browsers", function(){
  var browsers = new Array();
  for(var i=0; i < this.mTabs.length; i++)
    browsers.push(this.getBrowserForTab(this.mTabs[i]));
  return browsers;
});
gBrowser.mPanelContainer.__defineSetter__("selectedIndex", gBrowser.mPanelContainer.__lookupSetter__("selectedIndex") );
gBrowser.mPanelContainer.__defineGetter__("selectedIndex", function(){ return gBrowser.mTabContainer.selectedIndex; });
gBrowser.getBrowserAtIndex = function(aIndex){ return this.getBrowserForTab(this.mTabs[aIndex]); }

try {eval("bengoodger.com.tabdownloader._saveSubsequentTabs ="+bengoodger.com.tabdownloader._saveSubsequentTabs.toString().replace(
'var startBrowser = this._findNextBrowser(tabbrowser.selectedBrowser);',
'try{var startBrowser = tabbrowser.getBrowserAtIndex(tabbrowser.mCurrentTab._tPos+1);}catch(e){return;}'));
} catch(e){}

for(var i = 0; i < gBrowser.mTabs.length; i++)
{
 var uniqueId = "panel"+(new Date()).getTime()+i;
 gBrowser.mPanelContainer.childNodes[i].id = uniqueId;
 gBrowser.mTabs[i].linkedPanel = uniqueId;
 gBrowser.mTabs[i]._tPos = i;
}
if(gBrowser.mTabs.length > 0) gBrowser.mCurrentTab.selected = true;

gBrowser.mTabContainer.nextTab = 1;

eval("gBrowser.addTab ="+gBrowser.addTab.toString().replace(
'if (!blank)',
'var uniqueId = "panel"+(new Date()).getTime()+position; \
 this.mPanelContainer.lastChild.id = uniqueId; \
 t.linkedPanel = uniqueId; \
 t.linkedBrowser = b; \
 t._tPos = position; \
 if (t.previousSibling.selected) t.setAttribute("afterselected", true); \
 this.TMP_openTabNext(t, blank);\ $&'
 ));

eval("gBrowser.removeTab ="+gBrowser.removeTab.toString().replace(
'var l = this.mTabContainer.childNodes.length;',
'if (aTab.hasAttribute("protected")) return; $&'
).replace(
'this.mPanelContainer.removeChild(this.mPanelContainer.childNodes[index]);',
'this.mPanelContainer.removeChild(oldBrowser.parentNode);'
).replace(
'this.mPanelContainer.selectedIndex = newIndex;',
'newIndex = (this.mCurrentTab._tPos == 0 ? 0 : this.mCurrentTab._tPos-1); \
 for(var i = oldTab._tPos; i < this.mTabs.length; i++){this.mTabs[i]._tPos = i;} \
 this.mTabBox.selectedPanel = this.getBrowserForTab(this.mCurrentTab).parentNode; \
 this.mCurrentTab.selected = true; \
 SessionManager.tabClosed(oldTab);'
).replace(
'var oldTab = aTab;',
'$& saveClosedTab(oldTab, oldBrowser);'
).replace(
'this.selectedTab = this.mTabContainer.childNodes[newIndex];',
'this.mTabContainer.nextTab = 1; newIndex = this.selectAfterRemove(oldTab, newIndex); $&'
));

eval("gBrowser.onTitleChanged ="+gBrowser.onTitleChanged.toString().replace(
'var tab = tabBrowser.mTabContainer.childNodes[i];',
'var tab = document.getAnonymousElementByAttribute(tabBrowser, "linkedpanel", this.parentNode.id);'));

gBrowser.getBrowserForTab = function (aTab)
{
  var panel = document.getElementById(aTab.linkedPanel);
  return panel ? panel.firstChild.nextSibling : null;
}

} // end if(!getBrowser().moveTabTo)
else { // we in FF 1.5+ after bug 179656 Allow drag-and-drop reordering of tabs landed
if(gBrowser.mTabs.length > 0) gBrowser.mCurrentTab.selected = true;
gBrowser.mTabContainer.nextTab = 1;

eval("gBrowser.addTab ="+gBrowser.addTab.toString().replace(
'if (!blank)',
'var _caller = this.addTab.caller.name; \
 if (_caller != "sss_restoreWindow" && _caller != "sss_undoCloseTab") this.TMP_openTabNext(t, blank);\ $&'
));

eval("gBrowser.removeTab ="+gBrowser.removeTab.toString().replace(
'var l = this.mTabContainer.childNodes.length;',
'if (aTab.hasAttribute("protected")) return; $&'
).replace(
'var oldTab = aTab;',
'$& saveClosedTab(oldTab, oldBrowser);'
).replace(
'this.selectedTab = this.mTabContainer.childNodes[newIndex];',
'this.mTabContainer.nextTab = 1; newIndex = this.selectAfterRemove(oldTab, newIndex); $&'
).replace(
'oldBrowser.focusedElement = null;',
'$& SessionManager.tabClosed(oldTab);'
));

eval("gBrowser.mTabContainer.selectNewTab ="+gBrowser.mTabContainer.selectNewTab.toString().replace(
'{',
'{ if(!gPref.getBoolPref("extensions.tabmix.mouseDownSelect") && this.selectNewTab.caller.name == "setTab") return; '
));

eval("gBrowser.moveTabTo ="+gBrowser.moveTabTo.toString().replace(
'return aTab;',
'this.mTabContainer.ensureTabIsVisible(aTab._tPos); \ $&'
));

} // end of new eval after bug 179656 Allow drag-and-drop reordering of tabs landed

// bug 281012 - Closing the last tab loads an untitled page (about:blank) fixed in Firefox 2.0
if (gIsFirefox2) {
   eval("gBrowser.removeTab ="+gBrowser.removeTab.toString().replace(
      'this.addTab("about:blank");',
      'if (this.mPrefs.getBoolPref("extensions.tabmix.keepLastTab")) \ return; \
       $& \ setURLBarFocus();'
   ).replace( // update image and label that we use in closed tabs list
      'var evt = document.createEvent("Events")',
      'if (aTab.getAttribute("image") != this.getBrowserForTab(aTab).mIconURL) aTab.setAttribute("image", this.getBrowserForTab(aTab).mIconURL); \
       if (aTab.label == this.mStringBundle.getString("tabs.loading")) \ this.setTabTitle(aTab); \
       tabxTabClosed(aTab); \ $&'
   ));
}
else {
   eval("gBrowser.removeTab ="+gBrowser.removeTab.toString().replace(
      '(l == 1)',
      '(l == 1 && this.mPrefs.getBoolPref("browser.tabs.autoHide"))'
   ).replace(
      '(l == 2)',
      '(l == 1) { \ if (this.mPrefs.getBoolPref("extensions.tabmix.keepLastTab")) \ return; \
       this.addTab("about:blank"); l++; \
       setURLBarFocus();} else if $&'
   ).replace( // update image and label that we use in closed tabs list
      'var index = -1;',
      'if (aTab.getAttribute("image") != this.getBrowserForTab(aTab).mIconURL) aTab.setAttribute("image", this.getBrowserForTab(aTab).mIconURL); \
       if (aTab.label == this.mStringBundle.getString("tabs.loading")) \ this.setTabTitle(aTab); \
       tabxTabClosed(aTab); \ $&'
   ));
}

if (gIsFirefox2)
eval("BrowserCloseTabOrWindow ="+BrowserCloseTabOrWindow.toString().replace(
'gBrowser.removeCurrentTab();',
'if (gBrowser.tabContainer.childNodes.length > 1) $& \
 else closeLastTab();'
));

eval("BrowserCloseTabOrWindow ="+BrowserCloseTabOrWindow.toString().replace(
'BrowserCloseWindow();',
'closeLastTab();'
));

function closeLastTab() {
  if (gPref.getBoolPref("extensions.tabmix.keepWindow"))
    gBrowser.removeCurrentTab();
  else
    BrowserCloseWindow();
}

// for single window mode
eval("nsBrowserAccess.prototype.openURI ="+nsBrowserAccess.prototype.openURI.toString().replace(
'switch(aWhere)',
'tmLog("nsBrowserAccess.prototype.openURI " + aURI);if (gSingleWindowMode && aWhere == nsCI.nsIBrowserDOMWindow.OPEN_NEWWINDOW);\
 aWhere == nsCI.nsIBrowserDOMWindow.OPEN_NEWTAB;\
 $&'
));

// reuse current tab if it's blank tab for external link set to open new tab
if (gIsFirefox2) {
eval("nsBrowserAccess.prototype.openURI ="+nsBrowserAccess.prototype.openURI.toString().replace(
'var newTab = gBrowser.loadOneTab("about:blank", null, null, null, loadInBackground, false);',
'if (aOpener) gBrowser.fromLink = true; \
 var currentIsBlank = gBrowser.isBlankTab(gBrowser.mCurrentTab) && !gBrowser.mCurrentTab.hasAttribute("busy");\
 var newTab = currentIsBlank ? gBrowser.mCurrentTab : gBrowser.loadOneTab("about:blank", null, null, null, loadInBackground, false);\
 gBrowser.fromLink = false; \
 if (currentIsBlank) content.focus();'
));
}
else {
eval("nsBrowserAccess.prototype.openURI ="+nsBrowserAccess.prototype.openURI.toString().replace(
'var newTab = gBrowser.addTab("about:blank");',
'var currentIsBlank = gBrowser.isBlankTab(gBrowser.mCurrentTab) && !gBrowser.mCurrentTab.hasAttribute("busy");\
 var newTab = currentIsBlank ? gBrowser.mCurrentTab : gBrowser.addTab("about:blank");'
).replace(
'gBrowser.selectedTab = newTab;',
'{ if (currentIsBlank) content.focus();\
 else gBrowser.selectedTab = newTab; }'
));
}

//inverse focus of middle/ctrl/meta clicked links
eval("openNewTabWith ="+openNewTabWith.toString().replace(
'if (event && event.shiftKey)',
'if (event && (event.button == 1 || event.button == 0 && ( event.ctrlKey || event.metaKey )) && (prefSvc.getBoolPref("extensions.tabmix.inversefocusLinks") || !prefSvc.getBoolPref("extensions.tabmix.inversefocusLinks") && event.shiftKey))'
));

//inverse focus of middle/ctrl/meta clicked bookmarks/history
eval("whereToOpenLink ="+whereToOpenLink.toString().replace(
'var middle = !ignoreButton && e.button == 1;',
'var middle = "button" in e && !ignoreButton && e.button == 1;'
).replace(
'if (shift)',
'if (getBoolPref("extensions.tabmix.inversefocusOther", true) || (!getBoolPref("extensions.tabmix.inversefocusOther", true) && shift))'
));

//use bookmark labels when needed to
if ("constructGoMenuItem" in window)
eval("constructGoMenuItem ="+constructGoMenuItem.toString().replace(
'menuitem.setAttribute("statustext", url);',
'menuitem.setAttribute("statustext", url); \
 if ( gPref.getBoolPref("extensions.tabmix.titlefrombookmark") ) { \
 var bookMarkName = getTitleFromBookmark(url); \
 if (bookMarkName) title = bookMarkName;} '
));

eval("FillHistoryMenu ="+FillHistoryMenu.toString().replace(
/entry.title/g,
'menuItemTitle(entry)'
));

eval("gBrowser.updateTitlebar ="+gBrowser.updateTitlebar.toString().replace(
'if (!docTitle)',
'var aUrl = this.contentDocument.baseURI; aUrl = (aUrl) ? aUrl : this.currentURI.spec ; \
 if ( gPref.getBoolPref("extensions.tabmix.titlefrombookmark") ) { \
 var bookMarkName = getTitleFromBookmark(aUrl); \
 if (bookMarkName) docTitle = bookMarkName;} \
 var aTab = this.mCurrentTab; if (aTab.hasAttribute("label-uri") && aTab.getAttribute("label-uri") == aUrl) docTitle =aTab.getAttribute("fixed-label"); \
 if (!docTitle)'
));

eval("gBrowser.setTabTitle ="+gBrowser.setTabTitle.toString().replace(
'if (!title) {',
'var cIndex = this.mTabContainer.selectedIndex;\
 var currentTabVisible = this.mTabContainer.isTabVisible(cIndex);\
 var aUrl = browser.contentDocument.baseURI; aUrl = (aUrl) ? aUrl : browser.currentURI.spec ;\
 if ( gPref.getBoolPref("extensions.tabmix.titlefrombookmark") ) { \
 var bookMarkName = getTitleFromBookmark(aUrl); \
 if (bookMarkName) title = bookMarkName;} \
 if (aTab.hasAttribute("label-uri") && aTab.getAttribute("label-uri") == aUrl) title = aTab.getAttribute("fixed-label"); \
 if (!title) {'
).replace(
 'aTab.setAttribute("crop", crop);',
 '$& \ if (aTab.hasAttribute("mergeselected")) aTab.label = "(*) "+aTab.label; \
 if (TMP_getBoolPref(tabxBranch, "flexTabs", false) && TMP_getIntPref(tabxBranch, "maxWidth", 250) != TMP_getIntPref(tabxBranch, "minWidth", 30)) { \
 if (aTab.hasAttribute("width")) aTab.removeAttribute("width"); \
 tabBarScrollStatus(); checkBeforeAndAfter(); \
 if (currentTabVisible != this.mTabContainer.isTabVisible(cIndex)) this.mTabContainer.ensureTabIsVisible(cIndex);}'
));

// XXX content.focus(); here is to fix bug in FF trunk.....
eval("BrowserHomeClick ="+BrowserHomeClick.toString().replace(
'var where = whereToOpenLink(aEvent);',
'$& \ if (where == "current" && TMP_whereToOpen(false).inNew) where = "tab";'
).replace(
'gBrowser.loadTabs(urls, loadInBackground);',
'window.content.focus(); \ $&'
));

var searchbar = document.getElementById("searchbar");
// for firefox up to 1.5
if(searchbar && "mTextbox" in searchbar) {
eval("searchbar.mTextbox.onTextEntered ="+searchbar.mTextbox.onTextEntered.toString().replace(
'SearchLoadURL(searchURL, (evt && evt.altKey));',
'SearchLoadURL(searchURL, evt);'
).replace(
'SearchLoadURL(searchURL, (evt && evt.altKey || openInTab));',
'SearchLoadURL(searchURL, evt);'
).replace(
'SearchLoadURL(searchURL, ((evt && evt.altKey) ^ openInTab));',
'SearchLoadURL(searchURL, evt);'
));

// open new tab from "Add Engines.." if tab is lock or pref "extensions.tabmix.opentabfor.search" is true
// we dont need this in Firefox2
if (!gIsFirefox2)
eval("searchbar.mTextbox.onEnginePopupCommand ="+searchbar.mTextbox.onEnginePopupCommand.toString().replace(
'loadURI(regionBundle.getString("searchEnginesURL"), null, null);',
'var openNewTab = TMP_whereToOpen("extensions.tabmix.opentabfor.search").inNew; \
 if (openNewTab) { \
   var newTab = getBrowser().addTab(regionBundle.getString("searchEnginesURL")); \
   getBrowser().TMP_selectNewForegroundTab(newTab, false); \
   content.focus(); \
 } \
 else loadURI(regionBundle.getString("searchEnginesURL"), null, null);'
));

}

// XXX need to fix TMP_SearchLoadURL to work like in Fx 3.0
// #351253 [Firefox:Search]-Search button misinterprets modifiers when clicked [All]
//
// for firefox 2.0 +
// new handleSearchCommand in search.xml version 1.47 from bug 335441 2006-05-06
// Bug 336925: Middle clicking search button should open new tab search.xml version 1.67
if(searchbar && "handleSearchCommand" in searchbar)
eval("searchbar.handleSearchCommand ="+searchbar.handleSearchCommand.toString().replace(
'this.doSearch',
'TMP_SearchLoadURL(textValue, aEvent, true); if (aEvent) aEvent.stopPropagation(); return; \ $&'
));

// fix webSearch to open new tab if tab is lock
if("BrowserSearch" in window)
eval("BrowserSearch.webSearch ="+BrowserSearch.webSearch.toString().replace(
'loadURI(searchForm, null, null, false)',
'gBrowser.TMP_openURI(searchForm);'
));

// fix FeedHandler to open new tab if tab is lock
if("FeedHandler" in window)
eval("FeedHandler.buildFeedList ="+FeedHandler.buildFeedList.toString().replace(
'loadURI(feeds[0].href, null, null, false);',
'gBrowser.TMP_openURI(feeds[0].href);'
));

gBrowser.TMP_openURI = function (uri)
{
   var openNewTab = TMP_whereToOpen(true).lock;
   if (openNewTab)
      this.loadOneTab(uri, null, null, null, false, false);
   else 
      loadURI(uri, null, null, false);
}

eval("WindowIsClosing ="+WindowIsClosing.toString().replace(
'var reallyClose = browser.warnAboutClosingTabs(true);',
'var pref = "extensions.tabmix.warnAboutClosingTabs.timeout"; \
 var startTime = new Date().valueOf(); \
 var oldTime = gPref.prefHasUserValue(pref) ? gPref.getCharPref(pref) : 0; \
 var reallyClose = browser.warnAboutClosingTabs("All_onExit"); \
 gPref.setCharPref(pref, oldTime*1 + (new Date().valueOf() - startTime));'
).replace(
'return closeWindow(false);',
'{ \
  var _close = closeWindow(false); \
  if (_close) SessionManager.deinit(numberOfWindows() == 1, true); \
  return _close; \
 }'
));
window.tryToClose = WindowIsClosing;

eval("goQuitApplication ="+goQuitApplication.toString().replace(
'if (!canQuitApplication())',
'var winCount = numberOfWindows(true); \
 var curTime = new Date().valueOf(); \
 if (!canQuitApplication())'
).replace(
'domWindow.close();',
'var wintype = domWindow.document.documentElement.getAttribute("windowtype");\
 if (window && (wintype == "navigator:browser")) domWindow.SessionManager.deinit(winCount-- == 1, true, curTime); \
 domWindow.close();'
));

//overlay BrowserToolboxCustomizeDone
eval("BrowserToolboxCustomizeDone ="+BrowserToolboxCustomizeDone.toString().replace(
'if (aToolboxChanged) {',
'$&\ TMP_BrowserToolboxCustomizeDone();'
));

// with MR Tech's local install
// don't open trober in current tab when tab is locked
// or trober is to diffrent site then the current
if (typeof(Local_Install) == "object")
eval("Local_Install.openThrobber ="+Local_Install.openThrobber.toString().replace(
'local_common.openURL(local_common.getThrobberURL(), inNewTab);',
'var url = local_common.getThrobberURL(); \
 local_common.openURL(url, inNewTab ? inNewTab : TMP_checkCurrent(url) == "tab");'
));

// for firefox 2.0 +
// XXX this is temporary untile we use the build-in closedtabs list
if(gIsFirefox2){
eval("undoCloseTab ="+undoCloseTab.toString().replace(
'!gPrefService.getBoolPref("browser.tabs.autoHide") &&',
''
).replace(
'ss.undoCloseTab(window, aIndex || 0);',
'aIndex = aIndex || 0; var ctabs = gBrowser.closedTabs; \
 ctabs.splice(ctabs.length - 1 - aIndex, 1); \
 if (ctabs.length < 1) TMP_ClosedTabs.setButtonState(true); \
 $&'
));






// patch for bug 352524 [SessionStore] Exception when History menu clicked while SessionStore disabled
eval("HistoryMenu.toggleRecentlyClosedTabs ="+HistoryMenu.toggleRecentlyClosedTabs.toString().replace(
'var undoPopup = document.getElementById("historyUndoPopup");',
'$& \
 document.getElementById("historyUndoMenu").setAttribute("hidden", !window.__SSi); \
 document.getElementById("endUndoSeparator").setAttribute("hidden", !window.__SSi); \
 if (!window.__SSi) return;'
));

// add tab image and url in statustext to closed tab list
eval("HistoryMenu.populateUndoSubmenu ="+HistoryMenu.populateUndoSubmenu.toString().replace(
'var m = undoPopup.appendChild(document.createElement("menuitem"));',
'$& \ m.setAttribute("class", "menuitem-iconic bookmark-item"); \
 var tabData = undoItems[i].state; \
 var activeIndex = (tabData.index || tabData.entries.length) - 1; \
 m.setAttribute("statustext", tabData.entries[activeIndex].url); \
 m.setAttribute("image", TMP_SessionStore.getImage(tabData.xultab));'
).replace(
'undoPopup.appendChild(document.createElement("menuseparator"));',
'$& \ var _string = document.getElementById("tmp-string-bundle");\
 m = undoPopup.appendChild(document.createElement("menuitem")); \
 m.setAttribute("label", _string.getString("undoclosetab.clear.label")); \
 m.setAttribute("accesskey", _string.getString("undoclosetab.clear.accesskey")); \
 m.setAttribute("oncommand", "getClosedTab(null, -1);");'
));

var undoPopup = document.getElementById("historyUndoPopup")
undoPopup.setAttribute("oncommand", "event.stopPropagation();");
undoPopup.setAttribute("onclick", "closeMenus(event.target); event.stopPropagation();");

}

gBrowser.TMP_openTabNext = function (aTab, blank) {


  if (getBoolPref("extensions.tabmix.treemode", false)) {
    if (this.fromLink) {

      //indent of current tab
      var currentIndent = this.mCurrentTab.indent;

      //find position
      var pos = this.mCurrentTab._tPos + 1;
      var pTab = this.mCurrentTab.nextSibling;
      while (pTab) {
        if (pTab.indent <= currentIndent) break;
        pos++;
        pTab = pTab.nextSibling;
      }

      //set tab infos
      this.TMmoveTabTo(aTab, pos, 1);
      aTab.indent = currentIndent + 1;
    }
  } else {
    if (this.mPrefs.getBoolPref("extensions.tabmix.openTabNext")) {
      this.TMmoveTabTo(aTab, this.mCurrentTab._tPos + this.mTabContainer.nextTab,1);
    }
    if (this.mPrefs.getBoolPref("extensions.tabmix.openTabNextInverse")) 
      this.mTabContainer.nextTab++;
  }
}

gBrowser.TMmoveTabTo = function (aTab, aIndex, flag)
{
  if ( aTab._tPos == aIndex )
    return aTab;
  // splice, appendChild, insertBefore trigger tabxTabClosed and tabxTabAdded
  // we add this "tabmoved" attribute to test if it exsit in those function
  aTab.setAttribute("tabmoved", true);

  if(!(flag & 1)) this.mTabContainer.nextTab = 1;
  this._browsers = null; // invalidate cache
  this.mTabFilters.splice(aIndex,0,this.mTabFilters.splice(aTab._tPos, 1)[0]);
  this.mTabListeners.splice(aIndex,0,this.mTabListeners.splice(aTab._tPos, 1)[0]);

  var tabCount = this.mTabContainer.childNodes.length;
  var newPos = tabCount - 1 < aIndex ? tabCount - 1 : aIndex;
  var oldPosition = aTab._tPos;

  aIndex = aIndex < aTab._tPos ? aIndex: aIndex+1;

  if (aTab == this.mTabContainer.firstChild || aIndex == 0)
    this.mTabContainer.firstChild.removeAttribute("first-tab");
  if (aTab == this.mTabContainer.lastChild || tabCount <= aIndex)
    this.mTabContainer.lastChild.removeAttribute("last-tab");

  this.mCurrentTab.selected = false;
  // use .item() instead of [] because dragging to the end of the strip goes out of
  // bounds: .item() returns null (so it acts like appendChild), but [] throws
  this.mTabContainer.insertBefore(aTab, this.mTabContainer.childNodes.item(aIndex));
  aTab.updateIndent();
  // invalidate cache, because mTabContainer is about to change
  this._browsers = null;

  // Update "first-tab" and "last-tab" attributes
  if (!this.mTabContainer.firstChild.hasAttribute("first-tab"))
    this.mTabContainer.firstChild.setAttribute("first-tab", "true");
  if (!this.mTabContainer.lastChild.hasAttribute("last-tab"))
    this.mTabContainer.lastChild.setAttribute("last-tab", "true");

  var i;
  for (i = 0; i < tabCount; i++) {
     this.mTabContainer.childNodes[i]._tPos = i;
     /*  we don't need this if we update first-tab and last-tab here
        this line interfere with our "unreadTab" because it add "selected" false attribute to all tab
        even befor they selected
     this.mTabContainer.childNodes[i].selected = false; 
     */
  }
  this.mCurrentTab.selected = true;

  if (gIsFirefox2) {
    var evt = document.createEvent("UIEvents");
    evt.initUIEvent("TabMove", true, false, window, oldPosition);
    aTab.dispatchEvent(evt);
  }

  SessionManager.tabMoved(aTab, oldPosition, newPos);
  aTab.removeAttribute("tabmoved");

  this.mTabContainer.ensureTabIsVisible(aTab._tPos);

  return aTab;
}

gBrowser.duplicateTab = function (aTab, href)
{
  if (aTab.localName != "tab")
    aTab = this.mCurrentTab;
  var aBrowser = this.getBrowserForTab(aTab);
  var originalHistory = aBrowser.webNavigation.sessionHistory;
  var newTab = this.addTab();

  var newBrowser = this.getBrowserForTab(newTab);
  //try to set zoom factor befor we load content
  var zoomFactor = aBrowser.docShell.contentViewer ? aBrowser.markupDocumentViewer.textZoom : 1;
  setTextZoom(newBrowser, zoomFactor);

  var prop = SessionData.getTabProperties(aTab);
  SessionData.setTabProperties(newTab, prop);

  newBrowser.addEventListener('load', dupScrollPosition, true);
  //save scroll data and href to load after we clone tab history
  var bContent = aBrowser.contentWindow;
  newBrowser._scrollData = {
      tabPos: newTab._tPos,
      href: href,
      _scrollX: bContent.scrollX,
      _scrollY: bContent.scrollY,
      zoom: zoomFactor
  };

  dtMergeWindows.cloneTabHistory(newBrowser.webNavigation, dtMergeWindows.copyHistory(originalHistory));

  content.focus();
  var bgPref = this.mPrefs.getBoolPref("extensions.tabmix.loadNewInBackground");
  if (gIsFirefox2 && !bgPref)
     newTab.owner = aTab;
  this.TMP_selectNewForegroundTab(newTab, bgPref, aBrowser.currentURI.spec, false);

  if (this.mPrefs.getBoolPref("extensions.tabmix.openDuplicateNext")) {
    newTab.indent = aTab.indent;
    var pos = newTab._tPos > aTab._tPos ? 1 : 0;
    this.TMmoveTabTo(newTab, aTab._tPos+pos);
  }

  return newTab;
}


gBrowser.duplicateInWindow = function (aTab, removeTab)
{
  if (aTab.localName != "tab")
    aTab = this.mCurrentTab;

  if (!gSingleWindowMode) {
    var aBrowser = this.getBrowserForTab(aTab);
    var bContent = aBrowser.contentWindow;
    var zoomFactor = aBrowser.docShell.contentViewer ? aBrowser.markupDocumentViewer.textZoom : 1;
    var duplicatData = {
       scroll: bContent.scrollX + "," + bContent.scrollY + "," + zoomFactor,
       oldHistory: aBrowser.webNavigation.sessionHistory,
       prop: SessionData.getTabProperties(aTab)
    }
    if (removeTab) {  // if we want to remove the tab as well
      if (aTab.hasAttribute("protected"))
         aTab.removeAttribute("protected");
      // if we move the last tab close the window
      if (this.mTabContainer.childNodes.length == 1)
         window.needToClose = true;
      this.removeTab(aTab);
    }
    // if we remove the current tab we need time to get the new tab selected
    // befor we move the focus to the new window
    setTimeout(function() {
      var newWindow = window.openDialog( getBrowserURL(), "_blank", "chrome,all,dialog=no");
      newWindow.duplicat = true;
      newWindow.duplicatData = duplicatData;
    }, 0);
  } else {
    this.duplicateTab(aTab);
  }
}

gBrowser.openLinkWithHistory = function (aTab)
{
  var href = typeof(gContextMenu.linkURL) == "function"  ? gContextMenu.linkURL() : gContextMenu.linkURL;
  var linkNode = gContextMenu.link;
  var newTab = this.duplicateTab(aTab, href);

  // in Firefox 1.5, markLinkVisited() has been removed
  if (linkNode && "markLinkVisited" in window)
      TMP_markLinkVisited(href, linkNode);

  return true;
}

gBrowser.openHereWith = function ()
{
  var href = typeof(gContextMenu.linkURL) == "function"  ? gContextMenu.linkURL() : gContextMenu.linkURL;
  var referrerURI = ("makeURI" in window) ? makeURI(gContextMenu.docURL) : getReferrer(document); //also works with getRefferrer
  loadURI(href, referrerURI, null, false);
}

gBrowser.openInverseLink = function (aTab)
{
  var href = typeof(gContextMenu.linkURL) == "function"  ? gContextMenu.linkURL() : gContextMenu.linkURL;
  var linkNode = gContextMenu.link;
  var newTab = this.addTab(href);
  var bgPref = this.mPrefs.getBoolPref("browser.tabs.loadInBackground");

  this.TMP_selectNewForegroundTab(newTab, !bgPref, href);
  // in Firefox 1.5, markLinkVisited() has been removed
  if (linkNode && "markLinkVisited" in window)
      TMP_markLinkVisited(href, linkNode);

  return true;
}

gBrowser.closeAllTabs = function ()
{
   if (this.warnAboutClosingTabs("All")) {
      var childNodes = this.mTabContainer.childNodes;
      if (this.mTabContainer.collapsedTabs > 0)
         this.mTabContainer.collapsedTabs = 0;

      for (var i = childNodes.length - 1; i >= 0; --i) {
         if (childNodes[i] != this.mCurrentTab)
            this.removeTab(childNodes[i]);
      }
      this.removeTab(this.mCurrentTab);
      this.mTabContainer.ensureTabIsVisible(this.mCurrentTab._tPos);
   }
}

gBrowser.closeGroupTabs = function (aTab)
{
   if (aTab.localName != "tab")
      aTab = this.mCurrentTab;

   var URL = this.getBrowserForTab(aTab).currentURI.spec;
   var matches = URL.match(/(^.*\/)(.*)/);
   var aDomain = matches ?  matches[1] : URL;

   if (this.warnAboutClosingTabs("Group", null, null, aDomain)) {
      var childNodes = this.mTabContainer.childNodes;
      if (this.mTabContainer.collapsedTabs > 0)
         this.mTabContainer.collapsedTabs = 0;
      for ( i = childNodes.length - 1; i > -1; --i) {
         if (childNodes[i] != aTab &&
               this.getBrowserForTab(childNodes[i]).currentURI.spec.indexOf(aDomain) != -1)
            this.removeTab(childNodes[i]);
      }
      this.removeTab(aTab);
      this.mTabContainer.ensureTabIsVisible(this.mCurrentTab._tPos);
   }
}

gBrowser.closeRightTabs = function (aTab)
{
   if (aTab.localName != "tab")
      aTab = this.mCurrentTab;

   if (this.warnAboutClosingTabs("Right", aTab._tPos)) {
      if ( aTab._tPos < this.mCurrentTab._tPos )
         this.mTabContainer.selectedItem = aTab;

      var childNodes = this.mTabContainer.childNodes;
      for ( i = childNodes.length - 1; i > aTab._tPos; i-- )
         this.removeTab(childNodes[i]);
   }
}

gBrowser.closeLeftTabs = function (aTab)
{
   if (aTab.localName != "tab")
      aTab = this.mCurrentTab;

   if (this.warnAboutClosingTabs("Left", aTab._tPos)) {
      if ( aTab._tPos > this.mCurrentTab._tPos )
         this.mTabContainer.selectedItem = aTab;

      var childNodes = this.mTabContainer.childNodes;
      if (this.mTabContainer.collapsedTabs > 0)
         this.mTabContainer.collapsedTabs = 0;
      for ( i = aTab._tPos - 1; i >= 0; i-- )
         this.removeTab(childNodes[i]);
      this.mTabContainer.ensureTabIsVisible(this.mCurrentTab._tPos);
   }
}

gBrowser.removeAllTabsBut = function (aTab)
{
   if (aTab.localName != "tab")
      aTab = this.mCurrentTab;

   if (this.warnAboutClosingTabs("AllBut", null, aTab.hasAttribute("protected"))) {
      if (aTab != this.mCurrentTab)
         this.mTabContainer.selectedItem = aTab;

      var childNodes = this.mTabContainer.childNodes;
      if (this.mTabContainer.collapsedTabs > 0)
         this.mTabContainer.collapsedTabs = 0;
      for (var i = childNodes.length - 1; i >= 0; --i) {
         if (childNodes[i] != aTab)
            this.removeTab(childNodes[i]);
      }
      this.mTabContainer.ensureTabIsVisible(this.mCurrentTab._tPos);
   }
}

gBrowser.reloadLeftTabs = function (aTab)
{
  if (aTab.localName != "tab")
    aTab = this.mCurrentTab;
  var childNodes = this.mTabContainer.childNodes;
  if ( aTab._tPos > this.mCurrentTab._tPos )
    this.mTabContainer.selectedItem = aTab;
  for ( i = aTab._tPos - 1; i >= 0; i-- )
    this.reloadTab(childNodes[i]);
}

gBrowser.reloadRightTabs = function (aTab)
{
  if (aTab.localName != "tab")
    aTab = this.mCurrentTab;
  var childNodes = this.mTabContainer.childNodes;
  if ( aTab._tPos < this.mCurrentTab._tPos )
    this.mTabContainer.selectedItem = aTab;
  for ( i = childNodes.length - 1; i > aTab._tPos; i-- )
    this.reloadTab(childNodes[i]);
}

gBrowser.reloadAllTabsBut = function (aTab)
{
   if (aTab.localName != "tab")
    aTab = this.mCurrentTab;
   else
    this.mTabContainer.selectedItem = aTab;
   var childNodes = this.mTabContainer.childNodes;
   for (var i = childNodes.length - 1; i >= 0; --i) {
   if (childNodes[i] != aTab)
    this.reloadTab(childNodes[i]);
  }
}

gBrowser.undoRemoveTab = function ()
{
  if( !this.mPrefs.getBoolPref("extensions.tabmix.undoClose" ) || !this.closedTabs.length )
    return null;

  var aTab = getClosedTab("original", this.closedTabs.length-1);
  return this.restoreTab(aTab[0], aTab[1], aTab[4], aTab[5]);
}

gBrowser.delayUndoRemoveAllTab = function ()
{
   // call undoRemoveAllTab after delay to let the popup menu time to hide
   var _this = this;
   window.setTimeout( function () { _this.undoRemoveAllTab(); }, 0 );
}

gBrowser.undoRemoveAllTab = function ()
{
  var btn = document.getElementById("btn_undoclose");
  if (btn)
    btn.setAttribute("disabled", true);

  var aTab, blankTab, newTab, selectTab = true;
  // catch blank tab for reuse
  var blankTabs = [];
  if (!this.mPrefs.getBoolPref("extensions.tabmix.treemode")) {
    for (var i = 0; i < this.mTabs.length ; i++) {
      aTab = this.mTabs[i];
      if (this.isBlankTab(aTab) && !aTab.hasAttribute("busy")) {
        aTab.reuse = true;
        blankTabs.push(aTab);
      }
    }
  }

  while (this.closedTabs.length > 0) {
    aTab = getClosedTab("original", this.closedTabs.length-1);
    blankTab = blankTabs.pop();
    newTab = (blankTab) ? blankTab : this.addTab();

    this.restoreTabData(newTab, aTab[0], aTab[1], aTab[4], aTab[5], selectTab);
    selectTab = false;
  }

  // remove unused blank tabs
  while(blankTabs.length > 0){
    blankTab = blankTabs.pop();
    this.removeTab(blankTab);
  }

  this.mTabContainer.nextTab = 1
}

gBrowser.restoreTab = function TMP_restoreTab(ord, hist, prop, zoom) {
  var btn = document.getElementById("btn_undoclose");
  if (btn)
    btn.setAttribute("disabled", this.closedTabs.length < 1);

  // reuse blanke tab
  var newTab = this.mCurrentTab;
  if (this.mPrefs.getBoolPref("extensions.tabmix.treemode") || 
      !this.isBlankTab(newTab) || newTab.hasAttribute("busy"))
    newTab = this.addTab();

  this.restoreTabData(newTab, ord, hist, prop, zoom, true);
  return newTab;
}

gBrowser.restoreTabData = function TMP_restoreTabData(newTab, ord, hist, prop, zoom, selectTab) {
  var newBrowser = this.getBrowserForTab(newTab);

  if (zoom && zoom != "0,0,1") { //try to set zoom factor befor we load content
    var XYZ = zoom.split(",");
    setTextZoom(newBrowser, XYZ[2]);
  }

  var restorePosition = getBoolPref("extensions.tabmix.undoClosePosition", true );
  var newPos;
  if ( restorePosition ) {
    newPos = ord > this.mTabs.length - 1 ? this.mTabs.length - 1 : ord;
    if (this.mPrefs.getBoolPref("extensions.tabmix.treemode")) {
      if (newPos > 0) {
        var indent = this.mTabs[newPos - 1].indent;
        if (this.mTabs[newPos].indent > indent) {
          indent = this.mTabs[newPos].indent;
        }
      }
      newTab.indent = indent;
    }
    this.TMmoveTabTo(newTab, newPos);
  }
  else if (newTab.reuse) {
    // move reuse tabs to the end when restore all closed tabs list
    var openTabNext = this.mPrefs.getBoolPref("extensions.tabmix.openTabNext");
    newPos = openTabNext ? this.mCurrentTab._tPos + this.mTabContainer.nextTab++ : this.mTabs.length - 1;
    this.TMmoveTabTo(newTab, newPos, 1);
    if (newTab != this.mCurrentTab)
      newTab.removeAttribute("flst_id");
    delete newTab.reuse;
  }

  SessionData.setTabProperties(newTab, prop);

  var oldHistory = hist;
  var newHistory = newBrowser.webNavigation.sessionHistory;

  newHistory.QueryInterface(Components.interfaces.nsISHistoryInternal);
  for (var i = 0; i < oldHistory.count; i++) {
    newHistory.addEntry(oldHistory.getEntryAtIndex(i, false), true);
  }
  if( oldHistory.count ) {
    try { newBrowser.webNavigation.gotoIndex(oldHistory.index); } catch (e) {}
  }

  // call to set scroll Position for restored closed tab from prev session
  if (zoom && zoom != "0,0,1") {
     newBrowser.addEventListener('load', dupScrollPosition, true);
     newBrowser._scrollData = {
       tabPos: newTab._tPos,
       href: null,
       _scrollX: XYZ[0],
       _scrollY: XYZ[1],
       zoom: XYZ[2]
     }
  }

  if (selectTab) {
    content.focus();
    this.TMP_selectNewForegroundTab(newTab, false, null, false);
  }

  return newTab;
}

gBrowser.lockTab = function (aTab)
{
  if (aTab.localName != "tab")
    aTab = this.mCurrentTab;
  if ( aTab.hasAttribute("locked") ) {
    aTab.removeAttribute("locked");
    aTab.setAttribute("_locked", "false");
  }
  else {
    aTab.setAttribute("locked", "true");
    aTab.setAttribute("_locked", "true");
  }
  SessionManager.updateTabProp(aTab);
}

gBrowser.protectTab = function (aTab)
{
  if (aTab.localName != "tab")
    aTab = this.mCurrentTab;
  if ( aTab.hasAttribute("protected") )
    aTab.removeAttribute("protected");
  else
    aTab.setAttribute("protected", "true");
  SessionManager.updateTabProp(aTab);
}

gBrowser.freezeTab = function (aTab)
{
  if (aTab.localName != "tab")
    aTab = this.mCurrentTab;
  if ( !aTab.hasAttribute("protected") || !aTab.hasAttribute("locked")){
    aTab.setAttribute("protected", "true");
    aTab.setAttribute("locked", "true");
    aTab.setAttribute("_locked", "true");
  } else {
    aTab.removeAttribute("protected");
    aTab.removeAttribute("locked");
    aTab.setAttribute("_locked", "false");
  }
  SessionManager.updateTabProp(aTab);
}

gBrowser.SelectToMerge = function(aTab)
{
  if (gSingleWindowMode && numberOfWindows() == 1) return;
  if (aTab.localName != "tab")
    aTab = this.mCurrentTab;
  if (aTab.hasAttribute("mergeselected")) {
    aTab.removeAttribute("mergeselected");
    aTab.label = aTab.label.substr(4);
  } else {
    aTab.setAttribute("mergeselected", "true")
    aTab.label = "(*) "+aTab.label;
  }
}

gBrowser.onSetReloadTime = function(aTab, aReloadTime)
{
  if (aTab.localName != "tab")
    aTab = this.mCurrentTab;
  aTab.autoReloadTime = aReloadTime;
  gPref.setIntPref("extensions.tabmix.reload_time", aTab.autoReloadTime);
  this.enableAutoReload(aTab);
}

gBrowser.setupAutoReload = function (aTab)
{
  if (aTab.localName != "tab")
    aTab = this.mCurrentTab;
  aTab.autoReloadEnabled = false;
  aTab.autoReloadTime = gPref.getIntPref("extensions.tabmix.reload_time");
  aTab.autoReloadTimerID = null;
  aTab.postDataAcceptedByUser = false;
  aTab.id = "ActiveReloadTab" + autoReloadTabID;
   autoReloadTabID++;
}

gBrowser.onAutoReloadEnable = function (aTab)
{
  if (aTab.localName != "tab")
    aTab = this.mCurrentTab;
  if (aTab.autoReloadEnabled)
    this.disableAutoReload(aTab);
  else
    this.enableAutoReload(aTab);
}

gBrowser.enableAutoReload = function(aTab)
{
  aTab.autoReloadEnabled = true;
  aTab.autoReloadURI = this.getBrowserForTab(aTab).currentURI.spec;
  clearTimeout(aTab.autoReloadTimerID);
  aTab.autoReloadTimerID = setTimeout(reloadPage, aTab.autoReloadTime*1000, aTab.id);
  if (gIsFirefox2)
    aTab.setAttribute("reload-data", aTab.autoReloadURI + " " + aTab.autoReloadTime);
}

gBrowser.disableAutoReload = function (aTab)
{
  aTab.autoReloadEnabled = false;
  aTab.autoReloadURI = null;
  aTab.postDataAcceptedByUser = false;
  clearTimeout(aTab.autoReloadTimerID);
  if (gIsFirefox2)
    aTab.removeAttribute("reload-data");
}

gBrowser.onEnableAutoReloadAllTabs = function ()
{
  var tabs = this.mTabContainer.childNodes;
  for(var i=0; i<tabs.length; i++){
    var tab = tabs[i];
    if (tab.autoReloadEnabled == null)
      this.setupAutoReload(tab);
    if (tab.autoReloadEnabled != true)
      this.enableAutoReload(tab);
    else {
      var uri = this.getBrowserForTab(tab).currentURI.spec;
      if (tab.autoReloadURI != uri)
         tab.autoReloadURI = uri;
    }
  }
}

gBrowser.onDisableAutoReloadAllTabs = function ()
{
  var tabs = this.mTabContainer.childNodes;
  for(var i=0; i<tabs.length; i++){
    var tab = tabs[i];
    if (tab.autoReloadEnabled)
      this.disableAutoReload(tab);
  }
}

gBrowser.onAutoReloadCustom = function(aTab)
{
  if (aTab.localName != "tab")
    aTab = this.mCurrentTab;
  window.openDialog('chrome://tabtreemix/content/minit/autoReload.xul', '_blank', 'chrome,modal,centerscreen', autoReloadDialogResult);
  if (gAutoReloadDialogAccepted) {
    aTab.autoReloadTime = gPref.getIntPref("extensions.tabmix.custom_reload_time");
    this.enableAutoReload(aTab);
  }
}

gBrowser.onTabReloaded = function(aTab, aBrowser)
{
  if (aTab.autoReloadTimerID)
    clearTimeout(aTab.autoReloadTimerID);
  if (aTab.autoReloadURI == aBrowser.currentURI.spec) {
    if (aBrowser.curScrollX || aBrowser.curScrollY)
      aBrowser.contentWindow.scrollTo(aBrowser.curScrollX, aBrowser.curScrollY);
    aTab.autoReloadTimerID = setTimeout(reloadPage, aTab.autoReloadTime*1000, aTab.id);
  }
}

gBrowser.copyTabUrl = function (aTab)
{
  if (aTab.localName != "tab")
    aTab = this.mCurrentTab;
  var URL = this.getBrowserForTab(aTab).contentDocument.location;

  var clipboard = Components.classes["@mozilla.org/widget/clipboardhelper;1"]
                   .getService(Components.interfaces.nsIClipboardHelper);

  clipboard.copyString(URL);
}

gBrowser.renameTab = function(aTab)
{
   if (aTab.localName != "tab") aTab = this.mCurrentTab;
   var browser = this.getBrowserForTab(aTab);
   var doc = browser.contentDocument;
   var docTitle = doc.title ? doc.title : this.mStringBundle.getString("tabs.untitled");

   var data = {
      value: aTab.label,
      useTitle: false,
      docTitle: docTitle
   };
   window.openDialog('chrome://tabtreemix/content/minit/setFixedLabel.xul', '_blank', 'chrome,modal,centerscreen', data);
   var aNewLabel = data.value;

   if (aNewLabel == "cancel")
      return;

   var url = browser.currentURI.spec;
   if (aNewLabel)
      this.setFixLabel(aNewLabel, url, true);
   else {
      var title = docTitle;
      if ( gPref.getBoolPref("extensions.tabmix.titlefrombookmark") ) {
         var aUrl = doc.baseURI ? doc.baseURI : url ;
         var bookMarkName = getTitleFromBookmark(aUrl);
         if (bookMarkName) title = bookMarkName;
      }
      this.setFixLabel(title, url, false);
   }
}

gBrowser.setFixLabel = function (label, url, action)
{
   var i, wnd, aTab, browser, enumerator = windowEnumerator(), titleChanged = false;
   while (enumerator.hasMoreElements()) {
      wnd = enumerator.getNext();
      for (i = 0; i < wnd.gBrowser.mTabs.length; i++) {
         aTab = wnd.gBrowser.mTabs[i];
         browser = wnd.gBrowser.getBrowserForTab(aTab);
         if (browser.currentURI.spec == url) {
            if (aTab.getAttribute('label') != label) {
               aTab.setAttribute('label', label);
               titleChanged = true;
            }
            if (action) {
               aTab.setAttribute('fixed-label',label);
               aTab.setAttribute('label-uri',url)
            }
            else {
               aTab.removeAttribute('fixed-label');
               aTab.removeAttribute('label-uri');
            }
            if (aTab == wnd.gBrowser.mCurrentTab)
               wnd.gBrowser.updateTitlebar();
         }
      }
      if (titleChanged && TMP_getBoolPref(tabxBranch, "flexTabs", false)) {
         tabBarScrollStatus();
         checkBeforeAndAfter();
      }
   }
}

gBrowser.previousTabIndex = function (aTab)
{
  var temp_id, tempIndex = -1, max_id = 0;
  for (var i = 0; i < this.mTabs.length; ++i ) {
    temp_id = this.mTabs[i].getAttribute('flst_id');
    if (aTab && i == aTab._tPos)
      continue;
    if ( temp_id && temp_id > max_id ) {
      max_id = temp_id;
      tempIndex = i;
    }
  }
  return tempIndex;
}

gBrowser.previousTab = function (aTab)
{
  if (this.mTabs.length == 1) return;
  var tempIndex = this.previousTabIndex(aTab);

  // if no flst_id go to previousTab tab, from first tab go to the next tab
  if (tempIndex == -1)
    tempIndex = aTab._tPos == 0 ? 1 : aTab._tPos - 1;

  this.selectedTab = this.mTabs[tempIndex];
  this.mCurrentTab.focus();
}

gBrowser.selectAfterRemove = function (oldTab, index) {
   if (index >= this.mTabs.length) index = this.mTabs.length - 1;
   if (this.mCurrentTab != oldTab) return index;
   var l = this.mTabs.length;
   var currentIndex = oldTab._tPos;
   var mode = gPrefService.getIntPref("extensions.tabmix.focusTab");
   switch ( mode ) {
      case 0: // first tab
            return 0;
         break;
      case 1: // left tab
            return currentIndex == 0 ? 0 : currentIndex-1 ;
         break;
      case 2: // opener / right  (default )
            return index;
         break;
      case 3: // last tab
            return l - 1;
         break;
      case 4: // last selected
            if (l==1) return index;
            var tempIndex = this.previousTabIndex();
            return tempIndex > -1 ? tempIndex : index;
         break;
      case 5: // right tab
            return currentIndex == l ? currentIndex - 1 : currentIndex;
         break;
      default:
   }
   return index;
}

gBrowser.TMP_createTooltip = function (event)
{
   event.stopPropagation();
   var tn = document.tooltipNode;
   if (tn.localName != "tab")
      return false; // Not a tab, so cancel the tooltip
   if ("tmp_mOverCloseButton" in tn && tn.tmp_mOverCloseButton) {
      event.target.setAttribute("label", tn.getAttribute("closetabtext"));
      return true;
   }
   if (tn.hasAttribute("label")) {
      event.target.setAttribute("label", tn.getAttribute("label"));
      return true;
   }
   return false;
}

// return true if all tabs in the window are blank
gBrowser.isBlankWindow = function()
{
   for (var i = 0; i < this.mTabs.length; i++)
      if (!this.isBlankBrowser(this.getBrowserAtIndex(i))) return false;
   return true;
}

gBrowser.isBlankTab = function(aTab)
{
   return this.isBlankBrowser(this.getBrowserForTab(aTab));
}

gBrowser.isBlankBrowser = function(aBrowser)
{
   try{
      if (!aBrowser) return true;
      return (!aBrowser.sessionHistory || aBrowser.sessionHistory.index < 0 ||
         (aBrowser.sessionHistory.count < 2 &&
            (!aBrowser.currentURI || aBrowser.currentURI.spec == 'about:blank')));
   } catch (e) {return true;}
}

gBrowser.closeTab = function(aTab)
{
   // throws exception when rapid click on close tab button
   // we call this after delay
   if (!aTab.parentNode) return;
   if (this.mTabContainer.childNodes.length == 1 && this.isBlankTab(aTab) && !aTab.hasAttribute("busy") &&
      !this.mPrefs.getBoolPref("extensions.tabmix.keepLastTab")) {
         var urlBar = document.getElementById("urlbar");
         if (urlBar) {
            urlBar.value = "";
            urlBar.focus();
         }
   }
   else {
      // clear all timeouts befor we remove the tab
      if (aTab.isClosing) clearTimeout(aTab.isClosing);
      if (aTab.mSelect) clearTimeout(aTab.mSelect);
      if (aTab.mouseHoverSelect && aTab.mFocusId) {
         clearTimeout(aTab.mFocusId);
      }
      if (aTab.mButtonId) clearTimeout(aTab.mButtonId);
      this.removeTab(aTab);
      if (this.mTabContainer.childNodes.length == 1 && this.isBlankTab(this.mCurrentTab))
         setURLBarFocus();
      this.stopMouseHoverSelect(aTab);
   }
}

gBrowser.stopMouseHoverSelect = function(aTab)
{
   // add extra delay after tab removed or after tab flip befor we select by hover
   // to let the user time to move the mouse
   if (aTab.mouseHoverSelect) {
      function removeDelayAfterClose(browser) {
         browser.removeAttribute("preventMouseHoverSelect");
      }
      this.setAttribute("preventMouseHoverSelect",true);
      var delay = aTab.mouseHoverSelectDelay + 50;
      setTimeout(removeDelayAfterClose, delay, this);
   }
}

gBrowser.warnAboutClosingTabs =  function (whatToClose, tabPos, protectedTab, aDomain) {
   // try to cach call from other extensions to warnAboutClosingTabs
   if (typeof(whatToClose) == "boolean") {
      if (!whatToClose)
         protectedTab = this.mCurrentTab.hasAttribute("protected");
      whatToClose = whatToClose ? "All_onExit" : "AllBut";
   }
   
   var childNodes = this.mTabContainer.childNodes;
   var numTabs = childNodes.length;
   var shouldPrompt = 0;

   const tabsPref = "browser.tabs.warnOnClose";
   if (this.mPrefs.getBoolPref(tabsPref) && numTabs > 1)
      shouldPrompt = 1;

   // calc the number of tab to close when there is protected tabs.
   var protectedTabs = this.mTabContainer.getElementsByAttribute("protected", true);
   var numProtected = protectedTabs.length;

   const protectedTabsPref = "extensions.tabmix.protectedtabs.warnOnClose";
   if (numProtected > 0 && whatToClose == "All_onExit" &&
         this.mPrefs.getBoolPref(protectedTabsPref))
      shouldPrompt = 2;

   if (shouldPrompt == 0)
      return true;

   var i, tabsToClose = 0;
   switch (whatToClose) {
      case "All":
         tabsToClose = numTabs - numProtected;
         break;
      case "All_onExit":
         tabsToClose = numTabs;
         break;
      case "AllBut":
         if (protectedTab)
            --numProtected;
         tabsToClose = numTabs - 1 - numProtected;
         break;
      case "Group":
         for ( i = numTabs - 1; i > -1; --i) {
            if (this.getBrowserForTab(childNodes[i]).currentURI.spec.indexOf(aDomain) != -1 &&
                  !childNodes[i].hasAttribute("protected"))
               tabsToClose++;
         }
         break;
      case "Right":
         for ( i = 0; i < protectedTabs.length; i++ )
            if (protectedTabs[i]._tPos <= tabPos)
               --numProtected;
         tabsToClose = numTabs - tabPos - 1 - numProtected;
         break;
      case "Left":
         for ( i = 0; i < protectedTabs.length; i++ )
            if (protectedTabs[i]._tPos >= tabPos)
               --numProtected;
         tabsToClose = tabPos - numProtected;
         break;
   }

   if (tabsToClose <= 1 && shouldPrompt < 2)
      return true;

   var promptService = Components.classes["@mozilla.org/embedcomp/prompt-service;1"]
                                    .getService(Components.interfaces.nsIPromptService);

   //default to true: if it were false, we wouldn't get this far
   var warnOnClose = { value:true };
   var bundle = this.mStringBundle;

   var message, messageKey, chkBoxLabel;
   if (shouldPrompt != 2) {
      try {
         messageKey = (tabsToClose == 1) ? "tabs.closeWarningOne" : "tabs.closeWarningMultiple";
         message = bundle.getFormattedString(messageKey, [tabsToClose]);
      } catch (er) {
         messageKey = (tabsToClose == 1) ? "tabs.closeWarningOneTab" : "tabs.closeWarningMultipleTabs";
         message = bundle.getFormattedString(messageKey, [tabsToClose]);
      }
      chkBoxLabel = bundle.getString('tabs.closeWarningPromptMe');
   }
   else {
      var tmp_bundle = document.getElementById("tmp-string-bundle");
      messageKey = "protectedtabs.closeWarning.";
      messageKey += (numProtected < tabsToClose) ? "3" : (numProtected == 1) ? "1" : "2";
      message = tmp_bundle.getFormattedString(messageKey, [tabsToClose, numProtected]);
      chkBoxLabel = tmp_bundle.getString('protectedtabs.closeWarningPromptMe');
   }

   var closeKey = (tabsToClose == 1) ? "tabs.closeButtonOne" : "tabs.closeButtonMultiple";
   window.focus();
   var buttonPressed = promptService.confirmEx(window,
                                                bundle.getString('tabs.closeWarningTitle'),
                                                message,
                                                (promptService.BUTTON_TITLE_IS_STRING * promptService.BUTTON_POS_0)
                                                + (promptService.BUTTON_TITLE_CANCEL * promptService.BUTTON_POS_1),
                                                bundle.getString(closeKey),
                                                null, null,
                                                chkBoxLabel,
                                                warnOnClose);
   var reallyClose = (buttonPressed == 0);
   // don't set the pref unless they press OK and it's false
   if (reallyClose && !warnOnClose.value) {
      var pref = shouldPrompt != 2 ? tabsPref : protectedTabsPref;
      this.mPrefs.setBoolPref(pref, false);
   }

   return reallyClose;
}

gBrowser.TMP_selectNewForegroundTab = function (aTab, aLoadInBackground, aUrl, addOwner) {
   var bgLoad = (aLoadInBackground != null) ? aLoadInBackground :
                  this.mPrefs.getBoolPref("browser.tabs.loadInBackground");
   if (!bgLoad) {
      function _selectNewForegroundTab(browser, tab) {
         browser.selectedTab = tab;
         if (aUrl && aUrl == "about:blank")
            setURLBarFocus();
      }
      // set new tab owner
      addOwner = addOwner != null ? addOwner : true;
      if (gIsFirefox2 && addOwner)
         aTab.owner = this.selectedTab;
      setTimeout(_selectNewForegroundTab, 0, getBrowser(), aTab);
   }
   if (!bgLoad)
      this.selectedTab = aTab;
}

}} // end tablib

function setURLBarFocus() {
   var urlBar = document.getElementById("urlbar");
   if (urlBar)
      setTimeout(function() { urlBar.focus(); }, 10);
}

function dupScrollPosition(event) {
  var aBrowser = this;
  var data = aBrowser._scrollData;
  aBrowser.removeEventListener('load', dupScrollPosition, true);
  SessionManager.setScrollPosition(data.tabPos, data._scrollX, data._scrollY, 15, data.href, data.zoom);
  delete aBrowser._scrollData;
}

function setTextZoom(browser, zoomFactor) {
   try {
      if (browser.docShell.contentViewer == null) return; // probebly 1.0.7
      if (zoomFactor && browser.markupDocumentViewer.textZoom != zoomFactor)
         browser.markupDocumentViewer.textZoom = zoomFactor;
   } catch (e) {}
}

function menuItemTitle(entry) {
   if (gPref.getBoolPref("extensions.tabmix.titlefrombookmark") && entry.URI) {
      var bookMarkName = getTitleFromBookmark(entry.URI.spec);
      return bookMarkName ? bookMarkName : entry.title;
   }
   return entry.title;
}

function saveClosedTab(tab, browser) {
   if (tabxPrefs.getBoolPref("undoClose") && !gBrowser.isBlankBrowser(browser)) {
      var btn = document.getElementById("btn_undoclose");
      if (btn)
         btn.setAttribute("disabled","false");
      var bContent = browser.contentWindow;
      var zoomFactor = browser.docShell.contentViewer ? browser.markupDocumentViewer.textZoom : 1;
      gBrowser.closedTabs.push([tab._tPos,
                                 browser.sessionHistory,
                                 tab.getAttribute("label"),
                                 tab.getAttribute("image"),
                                 SessionData.getTabProperties(tab),
                                 bContent.scrollX + "," + bContent.scrollY + "," + zoomFactor
                              ]);
   }
   if (gBrowser.closedTabs.length > tabxPrefs.getIntPref("undoCloseCache"))
      gBrowser.closedTabs.shift();
   SessionManager.tabScrolled(tab);
}

var autoReloadTabID = 0;
var gAutoReloadDialogAccepted;

function autoReloadDialogResult(accepted){
  gAutoReloadDialogAccepted = accepted;
}

function reloadPage(autoReloadTabID){
  var aTab = document.getElementById(autoReloadTabID);
  if (aTab == null)
    return;

  var browser = gBrowser.getBrowserForTab(aTab);

  if (aTab.autoReloadEnabled == false ){
    aTab.postDataAcceptedByUser = false;
    return;
  }

  var loadFlags = nsIWebNavigation.LOAD_FLAGS_BYPASS_HISTORY | nsIWebNavigation.LOAD_FLAGS_BYPASS_PROXY | nsIWebNavigation.LOAD_FLAGS_BYPASS_CACHE;
  var entry = browser.webNavigation.sessionHistory.getEntryAtIndex(browser.webNavigation.sessionHistory.index, false);
  var postData = entry.QueryInterface(Components.interfaces.nsISHEntry).postData;
  var referrer = entry.QueryInterface(Components.interfaces.nsISHEntry).referrerURI;

  if ((postData!=null) && (aTab.postDataAcceptedByUser==false)){
    var params = Components.classes['@mozilla.org/embedcomp/dialogparam;1'].createInstance(Components.interfaces.nsIDialogParamBlock);
    var stringBundle = document.getElementById("tmp-string-bundle");
    params.SetString(12, stringBundle.getString('confirm_autoreloadPostData_title'));
    params.SetString(0,  stringBundle.getString('confirm_autoreloadPostData'));
    params.SetString(2, 'alert-icon');
    params.SetInt(2, 2);
    window.openDialog('chrome://global/content/commonDialog.xul', '_blank', 'chrome,modal,centerscreen', params);

    if (params.GetInt(0) == 0)
      aTab.postDataAcceptedByUser = true;
    else {
      aTab.autoReloadEnabled = false;
      return;
    }
  }
  browser.curScrollX = browser.contentWindow.scrollX;
  browser.curScrollY = browser.contentWindow.scrollY;

  var notifyFlags = Components.interfaces.nsIWebProgress.NOTIFY_ALL;
  browser.webNavigation.loadURI(browser.webNavigation.currentURI.spec, loadFlags, referrer, entry.postData, null);
}
